package org.darkforest.merchant.controller;

import org.apache.commons.lang.StringUtils;
import org.darkforest.common.services.StatOrderGoodsService;
import org.darkforest.common.services.StatService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.CsvUtil;
import org.darkforest.model.OrderStatistics;
import org.darkforest.dao.mapper.GoodsMapper;
import org.darkforest.model.GoodsStatistical;
import org.darkforest.model.SupplyChannelStatistics;
import org.darkforest.vo.MemberConsumptionStatisticVo;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by valentina on 15/4/29.
 * 统计计算控制类
 */
@Controller
@RequestMapping("stat")
public class StatController {

    @Autowired
    private StatService statService;

    @Autowired
    private StatOrderGoodsService statOrderGoodsService;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 统计概览
     *
     * @return
     */
    @RequestMapping("profile")
    public ModelAndView main(HttpServletRequest request) {
        ModelAndView res = new ModelAndView("stat/profile");

        Integer searchDay = 30;
        String searchScope = request.getParameter("searchScope");
        if (searchScope != null && !"".equals(searchScope)) {
            searchDay = Integer.valueOf(searchScope);
        }

        //得到店铺编号storeId
        StoreSellerVo sellerVo = (StoreSellerVo) request.getSession().getAttribute("sellerInfo");
        Integer storeId = sellerVo.getStoreId();

        OrderStatistics orderAmount = statOrderGoodsService.getOrderAmount(storeId);
        if (orderAmount == null) {
            orderAmount = new OrderStatistics();
            orderAmount.setsOrderAmount(new BigDecimal(0));
        }
        OrderStatistics orderAmountLimit = statOrderGoodsService.getOrderAmountLimit(searchDay, storeId);
        if (orderAmountLimit == null) {
            orderAmountLimit = new OrderStatistics();
            orderAmountLimit.setsOrderAmount(new BigDecimal(0));
            orderAmountLimit.setsOrderMemberCount(0);
        }
        OrderStatistics goodsCount = statOrderGoodsService.getGoodsCount(storeId);
        if (goodsCount == null) {
            goodsCount = new OrderStatistics();
            goodsCount.setsAllGoosCount(0);
            goodsCount.setsInSaleCount(0);
            goodsCount.setsOutSaleCount(0);
        }

        List<OrderStatistics> orderStatisticsList = statOrderGoodsService.statisticOrder(searchDay, storeId);

        //日期
        List<String> dates = new ArrayList<String>();
        //销量
        List<Float> sales = new ArrayList<Float>();
        for (OrderStatistics tmp : orderStatisticsList) {
            dates.add("'" + tmp.getsDate() + "'");
            sales.add(tmp.getsOrderAmount().floatValue());
        }

        res.addObject("searchScope", searchDay);
        res.addObject("orderAmount", orderAmount);
        res.addObject("orderAmountLimit", orderAmountLimit);
        res.addObject("goodsCount", goodsCount);
        res.addObject("dates", dates);
        res.addObject("sales", sales);

        return res;
    }

    /**
     * 商品分析
     *
     * @return
     */
    @RequestMapping("goods")
    public String goodsStat(HttpServletRequest request, @RequestParam(required = false, defaultValue = "1") int p) {
        //查询条件
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String startPrice = request.getParameter("startPrice");
        String endPrice = request.getParameter("endPrice");
        GoodsStatistical goodsStatistical = new GoodsStatistical();
        //改页处理用
        goodsStatistical.setStart(p);
        //得到店铺编号storeId
        StoreSellerVo sellerVo = (StoreSellerVo) request.getSession().getAttribute("sellerInfo");
        goodsStatistical.setStoreId(sellerVo.getStoreId());
        goodsStatistical.setStartDateStr(startDate);
        goodsStatistical.setEndDateStr(endDate);

        if (startPrice != null && !"".equals(startPrice)) {
            goodsStatistical.setStartPrice(new BigDecimal(startPrice));
        }
        if (endPrice != null && !"".equals(endPrice)) {
            goodsStatistical.setEndPrice(new BigDecimal(endPrice));
        }
        goodsStatistical.setResultList(goodsMapper.selectGoodsSales(goodsStatistical));
        request.setAttribute("pageBean", goodsStatistical);
        return "stat/goods";
    }

    /**
     * 会员消费统计
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "memberConsumpStatistic")
    public ModelAndView memberConsumpStatistic(String startTime,String endTime ,@RequestParam(required = false,defaultValue = "1")int p){
        ModelAndView res = new ModelAndView("stat/member_consump_statistic");
        MemberConsumptionStatisticVo memberConsumptionStatisticVo = new MemberConsumptionStatisticVo();
        memberConsumptionStatisticVo.setStart(p);
        memberConsumptionStatisticVo.setStartTime(StringUtils.isBlank(startTime) ? null : DateUtil.toUnixTimeStamp(startTime,DateUtil.DEFAULT_DATE_PATTERN));
        memberConsumptionStatisticVo.setEndTime(StringUtils.isBlank(endTime) ? null : DateUtil.toUnixTimeStamp(endTime,DateUtil.DEFAULT_DATE_PATTERN));

        memberConsumptionStatisticVo.setStartTimeStr(startTime);
        memberConsumptionStatisticVo.setEndTimeStr(endTime);

        List<MemberConsumptionStatisticVo> memberConsumptionStatisticVos = statOrderGoodsService.getMemberConsumpStatisticInfo(memberConsumptionStatisticVo);
        memberConsumptionStatisticVo.setResultList(memberConsumptionStatisticVos);
        res.addObject("pageBean", memberConsumptionStatisticVo);
        return res;
    }

    /****
     * 供货渠道统计
     */
    @RequestMapping("supplyChannel")
    public String supplyChannelStat(HttpServletRequest request, String startDate, String endDate,
                                    @RequestParam(required = false, defaultValue = "1") int p) {
        SupplyChannelStatistics supplyChannelStatistics = new SupplyChannelStatistics();
        supplyChannelStatistics.setStart(p);
        if (startDate != null && !startDate.equals(""))
            supplyChannelStatistics.setStartDate(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(DateUtil.strToDate(startDate, DateUtil.DEFAULT_DATE_PATTERN))));
        if (endDate != null && !endDate.equals(""))
            supplyChannelStatistics.setEndDate(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(DateUtil.strToDate(endDate, DateUtil.DEFAULT_DATE_PATTERN))));
        supplyChannelStatistics.setResultList(goodsMapper.selectSupplyChannelStatistics(supplyChannelStatistics));
        request.setAttribute("pageBean", supplyChannelStatistics);
        request.setAttribute("startDate",startDate);
        request.setAttribute("endDate",endDate);
        supplyChannelStatistics.setPageSwitch(false);
        List<SupplyChannelStatistics> list = goodsMapper.selectSupplyChannelStatistics(supplyChannelStatistics);
        String categories = "";
        String data = "";
        for (int i = 0; i < list.size(); i++) {
            SupplyChannelStatistics scs = list.get(i);
            categories += (scs.getGoodsSerial() != null && !scs.getGoodsSerial().equals("")) ? "\"" + scs.getGoodsSerial() + "\"" : "\"其他\"";
            if (list.size() - 1 > i) categories += ",";
            data += scs.getOrderSuccessNum() != null ? scs.getOrderSuccessNum() + "" : 0 + "";
            if (list.size() - 1 > i) data += ",";
        }
        request.setAttribute("categories", categories);
        request.setAttribute("data", data);
        return "stat/supply_channel";
    }

    /**
     * 流量统计
     *
     * @return
     */
    @RequestMapping("flow")
    public String flow() {
        return "stat/flow";
    }

    /**
     * 流量统计
     *
     * @return
     */
    @RequestMapping("flow_goods")
    public String flow_goods() {
        return "stat/flow_goods";
    }

    /**
     * 实物结算
     *
     * @return
     */
    @RequestMapping("settle")
    public String settle() {

        return "stat/settle";
    }

    @RequestMapping(value = "exportExcel")
    public String exportExcel(HttpServletRequest request, HttpServletResponse response, String startDate, String endDate) throws Exception {
        List exportData = new ArrayList<Map>();
        LinkedHashMap map = new LinkedHashMap();
        String fileName = "";
        SupplyChannelStatistics supplyChannelStatistics = new SupplyChannelStatistics();
        if (startDate != null && !startDate.equals(""))
            supplyChannelStatistics.setStartDate(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(DateUtil.strToDate(startDate, DateUtil.DEFAULT_DATE_PATTERN))));
        if (endDate != null && !endDate.equals(""))
            supplyChannelStatistics.setEndDate(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(DateUtil.strToDate(endDate, DateUtil.DEFAULT_DATE_PATTERN))));
//        supplyChannelStatistics.setResultList(goodsMapper.selectSupplyChannelStatistics(supplyChannelStatistics));
        supplyChannelStatistics.setPageSwitch(false);
        List<SupplyChannelStatistics> list = goodsMapper.selectSupplyChannelStatistics(supplyChannelStatistics);
        for (SupplyChannelStatistics scs : list) {
            Map row = new LinkedHashMap<String, String>();
            row.put("1", scs.getGoodsSerial()!=null&&!scs.getGoodsSerial().equals("")?scs.getGoodsSerial():"其他");
            row.put("2", scs.getGoodsSum()!=null?scs.getGoodsSum():"0");
            row.put("3", scs.getGoodsSellSum()!=null ? scs.getGoodsSellSum():"0");
            row.put("4", scs.getOrderNum()!=null?scs.getOrderNum():"0");
            row.put("5", scs.getOrderSuccessNum()!=null?scs.getOrderSuccessNum():"0");
            row.put("6", scs.getOrderAmount()!=null?scs.getOrderAmount():"0.00");
            row.put("7", scs.getOrderSuccessAmount()!=null?scs.getOrderSuccessAmount():"0.00");
            exportData.add(row);

        }
        map.put("1", "渠道商名称");
        map.put("2", "渠道商品总数");
        map.put("3", "渠道在售商品数量");
        map.put("4", "下单数量");
        map.put("5", "成交数量");
        map.put("6", "订单总金额");
        map.put("7", "成交总金额");
        fileName = "supply_channel_statistical";
        String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "temp\\";
        CsvUtil.createCSVFile(exportData, map, ctxPath, fileName);
        CsvUtil.downloadCSVFile(fileName + ".csv", ctxPath, request, response);
        return null;
    }
    @RequestMapping(value = "exportGoodsExcel")
    public String exportGoodsExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //查询条件
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String startPrice = request.getParameter("startPrice");
        String endPrice = request.getParameter("endPrice");
        List exportData = new ArrayList<Map>();
        LinkedHashMap map = new LinkedHashMap();
        GoodsStatistical goodsStatistical = new GoodsStatistical();
        //得到店铺编号storeId
        StoreSellerVo sellerVo = (StoreSellerVo) request.getSession().getAttribute("sellerInfo");
        goodsStatistical.setStoreId(sellerVo.getStoreId());
        goodsStatistical.setPageSwitch(false);
        goodsStatistical.setStartDateStr(startDate);
        goodsStatistical.setEndDateStr(endDate);

        if (startPrice != null && !"".equals(startPrice)) {
            goodsStatistical.setStartPrice(new BigDecimal(startPrice));
        }
        if (endPrice != null && !"".equals(endPrice)) {
            goodsStatistical.setEndPrice(new BigDecimal(endPrice));
        }
        List<GoodsStatistical> list = goodsMapper.selectGoodsSales(goodsStatistical);
        for (GoodsStatistical gs : list) {
            Map row = new LinkedHashMap<String, String>();
            row.put("1", gs.getGoodsName());
            row.put("2", gs.getGoodsCostPrice()!=null?gs.getGoodsCostPrice():"0.00");
            row.put("3", gs.getGoodsPrice()!=null?gs.getGoodsPrice():"0.00");
            row.put("4", gs.getGoodsSerial()!=null?gs.getGoodsSerial():"其他");
            row.put("5", gs.getSellNum()!=null?gs.getSellNum():"0");
            row.put("6", gs.getSellSum()!=null?gs.getSellSum():"0.00");
            exportData.add(row);

        }
        map.put("1", "商品名称");
        map.put("2", "成本");
        map.put("3", "当前售价");
        map.put("4", "渠道商");
        map.put("5", "购买数量");
        map.put("6", "销售金额");
        String fileName = "goods_statistical";
        String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "temp\\";
        CsvUtil.createCSVFile(exportData, map, ctxPath, fileName);
        CsvUtil.downloadCSVFile(fileName + ".csv", ctxPath, request, response);
        return null;
    }
}
